package org.gg.boom.common.controller;

import com.alibaba.fastjson2.JSONObject;
import com.google.code.kaptcha.Producer;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.gg.boom.common.constant.CacheConstants;
import org.gg.boom.common.model.RedisCache;
import org.gg.boom.common.model.Response;
import org.gg.boom.common.utils.sign.Base64;
import org.gg.boom.common.utils.uuid.IdUtils;
import org.gg.boom.kernel.config.GgBoomConfig;
import org.gg.boom.kernel.constant.Constants;
import org.gg.boom.modules.sys.service.SysConfigService;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static org.gg.boom.common.model.Response.success;

/**
 * 验证码操作处理
 */
@RestController
@RequiredArgsConstructor
public class CaptchaController {

    final Producer captchaProducer;

    final Producer captchaProducerMath;

    final RedisCache redisCache;

    final SysConfigService configService;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public Response getCode(HttpServletResponse response) throws IOException {
        JSONObject result = new JSONObject();
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        result.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled) {
            return success(result);
        }

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType = GgBoomConfig.getCaptchaType();
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return Response.error(e.getMessage());
        }

        result.put("uuid", uuid);
        result.put("img", Base64.encode(os.toByteArray()));
        return success(result);
    }


    /**
     * 获取二维码
     */
    @GetMapping("/getQrCode")
    public Response getQrCode() {
        return Response.success();
    }

}
